package cn.itcast.hotel.util;

import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.vo.PageResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class ResponseHandler {
    public static PageResult responseHandle(SearchResponse response){
        long total = response.getHits().getTotalHits().value;
        List<HotelDoc> list = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String jsonStr = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(jsonStr, HotelDoc.class);
//             获取高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField field = highlightFields.get("name");
//            判断是否存在高亮，是则替换hotelDoc中的name
            if (field!=null){
                String name = field.getFragments()[0].string();
                hotelDoc.setName(name);
            }
//            获取距离
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length>0){
                hotelDoc.setDistance(sortValues[0]);
            }

            log.warn("查询结果为{}",hotelDoc);
            list.add(hotelDoc);
        }
        return new PageResult(list,total);
    }
}
